import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Card, Typography, Space, Row, Col, message } from 'antd';
import { LoginOutlined, UserAddOutlined } from '@ant-design/icons';
import styled from 'styled-components';

const { Title, Text } = Typography;

// 声明 window.ethereum 的类型，避免 TypeScript 报错
declare let window: any;

const HomeContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #1890ff 0%, #722ed1 100%);
  padding: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const ContentCard = styled(Card)`
  max-width: 800px;
  width: 100%;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.95);
  padding: 40px 24px;
`;

const FeatureCard = styled(Card)`
  height: 100%;
  text-align: center;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  }
`;

const Home: React.FC = () => {
  const navigate = useNavigate();
  const [account, setAccount] = useState<string | null>(null);

  // 在组件加载时尝试连接 MetaMask
  useEffect(() => {
    const connectMetaMask = async () => {
      if (window.ethereum) {
        try {
          // 请求连接 MetaMask 账户
          const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
          if (accounts.length > 0) {
            setAccount(accounts[0]);
            message.success('MetaMask 连接成功！');
          }
        } catch (error: any) {
          // 用户拒绝连接或发生其他错误
          if (error.code === 4001) {
            message.warning('请连接 MetaMask 钱包以使用完整功能。');
          } else {
             message.error('MetaMask 连接失败：' + error.message);
          }
          console.error("MetaMask connection error:", error);
        }
      } else {
        // 用户没有安装 MetaMask
        message.warning('请安装 MetaMask 钱包以继续。');
      }
    };

    connectMetaMask();

    // 添加账户变化的监听器 (可选，但推荐)
    if (window.ethereum) {
        window.ethereum.on('accountsChanged', (accounts: string[]) => {
            if (accounts.length > 0) {
                setAccount(accounts[0]);
                message.info('MetaMask 账户已切换。');
            } else {
                setAccount(null);
                message.warning('MetaMask 账户已断开连接。');
            }
        });
    }

    // 组件卸载时移除事件监听器
    return () => {
        if (window.ethereum && window.ethereum.removeListener) {
             window.ethereum.removeListener('accountsChanged', (accounts: string[]) => {
                console.log('accountsChanged listener removed');
            });
        }
    };

  }, []);

  return (
    <HomeContainer>
      <ContentCard>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <div>
            <Title level={1} style={{ marginBottom: 16 }}>区块链投票系统</Title>
            <Text type="secondary" style={{ fontSize: 18 }}>
              基于区块链技术的安全、透明、可信的投票平台
            </Text>
          </div>

          <Row gutter={[24, 24]} style={{ marginTop: 48 }}>
            <Col xs={24} sm={8}>
              <FeatureCard>
                <Title level={4}>安全可靠</Title>
                <Text type="secondary">
                  基于区块链技术，确保投票过程的安全性和不可篡改性
                </Text>
              </FeatureCard>
            </Col>
            <Col xs={24} sm={8}>
              <FeatureCard>
                <Title level={4}>透明公开</Title>
                <Text type="secondary">
                  所有投票记录公开透明，可追溯可验证
                </Text>
              </FeatureCard>
            </Col>
            <Col xs={24} sm={8}>
              <FeatureCard>
                <Title level={4}>便捷高效</Title>
                <Text type="secondary">
                  简单易用的界面，快速创建和参与投票
                </Text>
              </FeatureCard>
            </Col>
          </Row>

          <div style={{ marginTop: 48 }}>
            <Space size="large">
              <Button
                type="primary"
                size="large"
                icon={<LoginOutlined />}
                onClick={() => navigate('/login')}
              >
                登录
              </Button>
              <Button
                size="large"
                icon={<UserAddOutlined />}
                onClick={() => navigate('/register')}
              >
                注册
              </Button>
            </Space>
          </div>
        </Space>
      </ContentCard>
    </HomeContainer>
  );
};

export default Home; 